package cc.fs.zhihuapp.ui.activity.demo;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.TrafficStats;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.model.VideoBean;
import cc.fs.zhihuapp.rest.asynchttp.VideoApi;
import cc.fs.zhihuapp.ui.activity.helper.BaseActivity;
import cc.fs.zhihuapp.utils.TimeUtil;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

/**
 * Created by fostion on 2015/10/28.
 * 没有缓存
 */
public class MyVideoActivity extends BaseActivity {

    @InjectView(R.id.surfaceView)
    SurfaceView videoView;
    @InjectView(R.id.backBtn)
    ImageView backBtn;
    @InjectView(R.id.playBtn)
    ImageView playBtn;
    @InjectView(R.id.forwardBtn)
    ImageView forwardBtn;
    @InjectView(R.id.bottomTab)
    LinearLayout bottomTab;
    @InjectView(R.id.progressbar)
    SeekBar progressbar;
    @InjectView(R.id.time)
    TextView time;
    @InjectView(R.id.bottomLayout)
    RelativeLayout bottomLayout;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.progressDialog)
    RelativeLayout progressDialog;
    @InjectView(R.id.speed)
    TextView speed;

    Timer timer;
    MyTimeTask myTimeTask;

    Timer networkTimer;
    NetworkTimeTask networkTimeTask;
    IjkMediaPlayer ijkplayer;
    SurfaceHolder surfaceHolder;

    VideoBean video;

    Animation outBottomAnimation;
    Animation inBottomAnimation;
    Animation outTopAnimation;
    Animation inTopAnimation;

    public static void start(Context context,VideoBean video){
        Intent intent = new Intent(context,MyVideoActivity.class);
        intent.putExtra("video",video);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_video);
        ButterKnife.inject(this);



        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setTitle("电影播放器");
        setSupportActionBar(toolbar);

        networkTimer = new Timer();
        networkTimeTask = new NetworkTimeTask();
        networkTimer.schedule(networkTimeTask,0,1000);

//        View dialogView = getLayoutInflater().inflate(R.layout.item_progress_dialog, null);
//        progressDialog = new AlertDialog.Builder(this, R.style.progressDialogTheme)
//                .setView(dialogView)
//                .setCancelable(false)
//                .create();
//        String url = "http://qiubai-video.qiushibaike.com/MRI2HAG8T5FGJGE3.mp4";
//        String url = "http://ssports.vod.smgbb.cn.cloudcdn.net/otv/vod/auto_bbf0913484a59baedb5d694236a45cc2.m3u8";
//        String url = "http://pl.youku.com/playlist/m3u8?ts=1440487880&keyframe=0&vid=XNjg4MDkxNDc2&type=3gphd&ep=dSaQGk2FUcYI5SPXgDsYZC%2B2cX8LXJZ0rEiB%2FKY5SMVQG%2BrQmzbWxg%3D%3D&sid=74404878800885133d584&token=2871&ctype=12&ev=1&oip=2035107507";
//        String url = "http://192.168.1.101:8080/video/movie.mp4";
        //中文名称后台无法识别需要编码
        video = this.getIntent().getParcelableExtra("video");
        speed.setVisibility(View.GONE);
        String url = VideoApi.HOST+"/static/" + URLEncoder.encode(video.getTitle());

//        String url = "http://192.168.10.123:8080/video/movie2.flv";
        setUpView(url);
    }

    private void setUpView(final String url) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        outBottomAnimation = AnimationUtils.loadAnimation(this, R.anim.bottom_play_out);
        inBottomAnimation = AnimationUtils.loadAnimation(this, R.anim.bottom_play_in);
        outTopAnimation = AnimationUtils.loadAnimation(this, R.anim.top_play_out);
        inTopAnimation = AnimationUtils.loadAnimation(this, R.anim.top_play_in);

        myTimeTask = new MyTimeTask();
        surfaceHolder = videoView.getHolder();
        surfaceHolder.setFixedSize(480, 720);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        inBottomAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                bottomLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        outBottomAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                bottomLayout.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        outTopAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                toolbar.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        inTopAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                toolbar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        videoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bottomLayout.getVisibility() == View.VISIBLE) {
                    bottomLayout.startAnimation(outBottomAnimation);
                } else {
                    bottomLayout.startAnimation(inBottomAnimation);
                }

                if (toolbar.getVisibility() == View.VISIBLE) {
                    toolbar.startAnimation(outTopAnimation);
                } else {
                    toolbar.startAnimation(inTopAnimation);
                }
            }
        });

        progressbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (ijkplayer != null && ijkplayer.isPlaying()) {
                    myTimeTask.isUpdate = false;
                    runDelay(new Runnable() {
                        @Override
                        public void run() {
                            long offsetTime = ijkplayer.getCurrentPosition() + getOffsetTime(progressbar.getProgress(), ((Number) ijkplayer.getCurrentPosition()).intValue());
                            ijkplayer.seekTo(offsetTime);
                            myTimeTask.isUpdate = true;
                        }
                    }, 50);
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ijkplayer != null && ijkplayer.isPlaying()) {
                    long position = ijkplayer.getCurrentPosition() - 20000;
                    ijkplayer.seekTo(position);
                    progressbar.setVisibility(View.VISIBLE);
                }
            }
        });

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ijkplayer != null) {
                    if (ijkplayer.isPlaying()) {
                        ijkplayer.pause();
                        playBtn.setImageResource(R.drawable.icon_play);
                    } else {
                        ijkplayer.start();
                        playBtn.setImageResource(R.drawable.icon_pause);
                    }
                } else {
                    try {
                        playBtn.setImageResource(R.drawable.icon_pause);
                        ijkplayer = new IjkMediaPlayer();
                        ijkplayer.setOnBufferingUpdateListener(new IMediaPlayer.OnBufferingUpdateListener() {
                            @Override
                            public void onBufferingUpdate(IMediaPlayer mp, int percent) {
                                progressbar.setSecondaryProgress(percent);
                            }
                        });

                        ijkplayer.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(IMediaPlayer mp, int what, int extra) {
                                progressDialog.setVisibility(View.GONE);
                                playBtn.setImageResource(R.drawable.icon_play);
                                ijkplayer = null;
                                Toast.makeText(_this, "网路异常，请稍后再试!", Toast.LENGTH_SHORT).show();
                                return false;
                            }
                        });

                        ijkplayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(IMediaPlayer mp) {
                                progressDialog.setVisibility(View.GONE);
                                timer = new Timer();
                                timer.schedule(myTimeTask, 0, 500);
                            }
                        });

                        ijkplayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(IMediaPlayer mp) {
                                onStop();
                                finish();
                            }
                        });

                        ijkplayer.setLogEnabled(true);
                        ijkplayer.setDisplay(surfaceHolder);
                        ijkplayer.setDataSource(url);
                        ijkplayer.prepareAsync();
                        progressDialog.setVisibility(View.VISIBLE);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        forwardBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long position = ijkplayer.getCurrentPosition() + 20000;
                ijkplayer.seekTo(position);
            }
        });

        progressbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }

    int getOffsetTime(int clickTime, int nowTime) {
        int cTime = clickTime;
        int nTime = nowTime;
        return cTime - nTime;
    }

    @Override
    protected void onStop() {
        networkTimer.cancel();
        networkTimeTask.cancel();
        if (myTimeTask != null) {
            myTimeTask.isUpdate = false;
            myTimeTask.cancel();
        }

        if (timer != null) {
            timer.cancel();
        }

        if (ijkplayer != null) {
            if(ijkplayer.isPlaying())
                ijkplayer.stop();
            ijkplayer.release();
        }
        super.onStop();
    }

    @Override
    public void handler(Message msg) {

    }

    class MyTimeTask extends TimerTask {
        boolean isUpdate = true;

        @Override
        public void run() {
            if (ijkplayer != null) {
                if (isUpdate) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressbar.setMax(((Number) ijkplayer.getDuration()).intValue());
                            progressbar.setProgress(((Number) ijkplayer.getCurrentPosition()).intValue());
                            time.setText(TimeUtil.formatVideoTime(progressbar.getProgress()) + "/" + TimeUtil.formatVideoTime(progressbar.getMax()));
                        }
                    });
                }
            }
        }
    }

    class NetworkTimeTask extends TimerTask {

        private long lastTotalRxBytes = 0;
        private long lastTimeStamp = 0;

        private long getTotalRxBytes() {
            return TrafficStats.getUidRxBytes(getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
        }

        @Override
        public void run() {
            long nowTotalRxBytes = getTotalRxBytes();
            long nowTimeStamp = System.currentTimeMillis();
            final long networkSpeed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

            lastTimeStamp = nowTimeStamp;
            lastTotalRxBytes = nowTotalRxBytes;

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    speed.setText(networkSpeed+"kb/s");
                }
            });

        }
    }

}
